<template>
	<view class="cc-tabs-wrap">
		<view class="tab-header">
			<view v-for="(tab, index) in tabList" :key="index" class="tab-item"
				:class="[innerActiveTab == index?'active':'']" @click="handleTabClick(index)">
				<view> {{ tab.title }} </view>
			</view>
		</view>
		<!-- 指示条 -->
		<view class="underline" :style="underlineStyle"></view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch,
		computed,
		getCurrentInstance,
		nextTick,
	} from 'vue'

	const {
		proxy
	} = getCurrentInstance();

	const emit = defineEmits(['update:modelValue', 'tabChange'])

	const props = defineProps({
		tabList: {
			type: Array,
			required: true
		},
		// Tab 索引
		modelValue: {
			type: Number,
			default: 0
		},
		underlineWidth: {
			type: Number,
			default: 25
		}
	})

	// 当前激活的 Tab
	const innerActiveTab = ref(props.modelValue)
	// 指示条位置
	const underlineLeft = ref(0)

	const underlineStyle = computed(() => {
		return {
			width: `${props.underlineWidth}px`,
			transform: `translateX(${underlineLeft.value}px)`
		};
	});

	watch(
		() => props.modelValue,
		(newValue) => {
			calculateUnderlinePosition(newValue);
			innerActiveTab.value = newValue;
		}, {
			deep: true
		}
	);

	watch(
		() => props.tabList,
		(newValue) => {
			nextTick(() => {
				initUnderline();
			})
		}, {
			deep: true,
			immediate: true
		}
	);
	
	onMounted(() => {
		initUnderline();
	})

	// 初始化指示条位置和宽度
	const initUnderline = () => {
		nextTick(() => {
			calculateUnderlinePosition(innerActiveTab.value);
		});
	}

	// 计算指示条位置
	const calculateUnderlinePosition = (index) => {
		const query = uni.createSelectorQuery().in(proxy);		
		query.selectAll('.tab-item').boundingClientRect(res => {
			if (res && res[index]) {
				// 偏移量
				let offset = (res[index].width - props.underlineWidth) / 2;
				underlineLeft.value = res[index].left + offset;
			}
		}).exec();
	}

	const handleTabClick = (index) => {
		if (index != innerActiveTab.value) {
			innerActiveTab.value = index;
			emit("update:modelValue", index);
			emit("tabChange", index);
		}
	}
</script>

<style lang="scss" scoped>
	.cc-tabs-wrap {
		width: 100%;
		display: flex;
		flex-direction: column;

		.tab-header {
			display: flex;
			position: relative;
			// 可根据需要调整为 space-between 或 flex-start
			justify-content: space-around;
			align-items: center;
			padding: 20rpx 0;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;
		}

		.tab-item {
			padding: 16rpx 24rpx 10rpx 24rpx;
			font-size: 30rpx;
			color: #666;
			display: flex;
			flex-direction: column;
			align-items: center;
			transition: color 0.3s ease;
			position: relative;
			z-index: 2;
			flex-shrink: 0;

			&.active {
				color: #000;
			}
		}

		.underline {
			position: absolute;
			bottom: 0;
			height: 4rpx;
			width: 20px;
			background-color: #000;
			transition: all 0.3s ease;
			border-radius: 3rpx;
		}
	}
</style>